<template>
    <a-config-provider :locale="zhCN">
    <a-button class="editable-add-btn" type="primary" @click="modal2Visible = true">
        添加书籍
    </a-button>
    <a-modal v-model:visible="modal2Visible" title="添加书籍" centered @ok="handAddBook" ok-text="确认"
      cancel-text="取消">
        <b>书籍名称：</b><a-input v-model:value="book_name" placeholder="输入新增书籍名称" style="margin-bottom:10px;"></a-input>
        <b>书籍编码：</b><a-input v-model:value="book_code" placeholder="输入新增书籍编码" style="margin-bottom:10px;"></a-input>
        <b>书籍作者：</b><a-input v-model:value="book_author" placeholder="输入新增书籍作者"></a-input>
    </a-modal>

    <a-modal v-model:visible="modal2Borrow" title="借书" centered @ok="onBorrowBook" ok-text="确认"
      cancel-text="取消">
        <b style="margin-bottom:10px;">书籍id：</b>{{ toBeBorrowBookId }}<br />
        <b style="margin-bottom:10px;">书籍名：</b>{{ toBeBorrowBookName }}<br />
        <b style="margin-bottom:10px;">选择借阅人：</b><a-select
            v-model:value="value"
            show-search
            placeholder="下拉选择借阅人"
            style="width: 200px"
            :options="borrowers_options"
            :filter-option="filterBorrowOption"
            @focus="handleBorrowFocus"
            @blur="handleBorrowBlur"
            @change="handleBorrowChange"
        ></a-select>
    </a-modal>

    <a-modal v-model:visible="modal2BorrowedHis" :title="`${hisBookName} 借阅历史`" width="1000px" centered @ok="modal2BorrowedHis = false" ok-text="确认"
      cancel-text="取消">
        <!-- <a-list size="small" bordered :data-source="bookBorrowedHis">
            <template #renderItem="{ item }">
                <a-list-item>{{ item }}</a-list-item>
            </template>
            <template #header>
                sssfd
            </template>
        </a-list> -->
        <a-table bordered :data-source="bookBorrowedHis" :columns="hisColumns" size="small" :loading="loading" :pagination="{ showTotal: bookHisTotal => `共${bookHisTotal}条借阅记录` }">
            <template #headerCell="{ column }">
                <template v-if="column.dataIndex === 'all_time'">
                <span>
                    借阅天数（天）
                    <span style="color:#1890ff;">
                    <a-tooltip placement="topLeft" title="如果有还书时间，还书时间减去借书时间；如果处于借阅中，当前时间减去借书时间。最终转换为天数，不足1天，向上取整。">
                        <info-circle-outlined />
                    </a-tooltip>
                    </span>
                </span>
                </template>
            </template>
            <template #bodyCell="{ column, text, record }">
                <template v-if="column.dataIndex === 'return_time'">
                    <template v-if="text == undefined"><a-tag color="darkred">借阅中</a-tag>
                    </template>
                    <template v-else>
                        {{ record.return_time.substr(0,4) }}-{{ text.substr(4,2) }}-{{ text.substr(6,2) }} {{ text.substr(8,2) }}:{{ text.substr(10,2) }}:{{ text.substr(12) }}
                    </template>
                </template>
                <template v-if="column.dataIndex === 'borrower_time'">
                    {{ text.substr(0,4) }}-{{ text.substr(4,2) }}-{{ text.substr(6,2) }} {{ text.substr(8,2) }}:{{ text.substr(10,2) }}:{{ text.substr(12) }}
                </template>
            </template>
        </a-table>
    </a-modal>

    <a-table 
        bordered 
        :data-source="books" 
        :columns="columns" 
        size="small" 
        class="ant-table-striped" 
        :row-class-name="(_record, index) => (index % 2 === 1 ? 'table-striped' : null)" 
        :loading="loading"
        :pagination="{ showSizeChanger: true, showTotal: bookTotal => `共${bookTotal}条` }"
        :scroll="{ y: 700 }"
    >
        <template #bodyCell="{ column, text, record }">
            <template v-if="column.dataIndex === 'book_valid'">
                <template v-if="text === 0"><a-tag color="volcano">下架</a-tag></template>
                <template v-else><a-tag color="green">上架</a-tag></template>
            </template>
            <template v-if="column.dataIndex === 'borrow_status'">
                <template v-if="record.book_valid">
                    <template v-if="text === 0"><a-tag color="darkred">已借出</a-tag></template>
                    <template v-else><a-tag color="geekblue">空闲</a-tag></template>
                </template>
                <template v-else>
                    --
                </template>
            </template>
            <template v-if="column.dataIndex === 'creation_ts'">
                {{ text.substr(0,4) }}-{{ text.substr(4,2) }}-{{ text.substr(6,2) }} {{ text.substr(8,2) }}:{{ text.substr(10,2) }}:{{ text.substr(12) }}
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
                <div>
                    <template v-if="record.book_valid == 0">
                        <a-popconfirm title="确定操作上架吗?" @confirm="onUpdateBookValid(record.id)" ok-text="确认"
      cancel-text="取消">
                            <a>上架</a>
                        </a-popconfirm>

                        &nbsp;

                        <a-popconfirm title="确定操作下架吗?" @confirm="onUpdateBookValid(record.id)" disabled>
                            <a disabled>下架</a>
                        </a-popconfirm>

                        &nbsp;

                    </template>
                    <template v-else-if="record.book_valid != 0">
                        <a-popconfirm title="确定操作上架吗?" @confirm="onUpdateBookValid(record.id)" disabled>
                            <a disabled>上架</a>
                        </a-popconfirm>
                        &nbsp;
                        <a-popconfirm title="确定操作下架吗?" @confirm="onUpdateBookValid(record.id)" ok-text="确认"
      cancel-text="取消">
                            <a>下架</a>
                        </a-popconfirm>
                        &nbsp;
                        <template v-if="record.borrow_status == 0">
                            <a disabled>借用</a>
                            &nbsp;
                            <a-popconfirm title="确定操作归还吗?" @confirm="onReturnBook(record.id)" ok-text="确认"
      cancel-text="取消">
                                <a>归还</a>
                            </a-popconfirm>
                        </template>
                        <template v-else-if="record.borrow_status != 0">
                            <!-- <a-popconfirm title="确定操作借用吗?" @confirm="onBorrowBook(record.id)"> -->
                                <a @click="onOpenBorrowModal(record.id,record.book_name)">借用</a>
                            <!-- </a-popconfirm> -->
                            &nbsp;
                            <a-popconfirm title="确定操作归还吗?" @confirm="onReturnBook(record.id)" disabled>
                                <a disabled>归还</a>
                            </a-popconfirm>
                        </template>
                    </template>
                    &nbsp;
                    <template style="display:inline;">
                        <a @click="onOpenBookBorrowedHisModal(record.id,record.book_name)">借阅记录</a>
                    </template>
                </div>
            </template>
        </template>
    </a-table>
</a-config-provider>
</template>

<script>
import { message } from "ant-design-vue";
import axios from "axios";
import { defineComponent, onMounted, ref } from "vue";
import { InfoCircleOutlined } from '@ant-design/icons-vue'
import zhCN from 'ant-design-vue/es/locale/zh_CN'

export default defineComponent(
    {
        name: 'Books',
        components:{
            InfoCircleOutlined,
        },
        setup() {
            const modal2Visible = ref(false);
            const modal2Borrow = ref(false);
            const modal2BorrowedHis = ref(false);
            const bookTotal = ref(0);
            const bookHisTotal = ref(0);
            const bookBorrowedHis = ref();
            const hisBookName = ref();
            const toBeBorrowBookId = ref(0);
            const toBeBorrowBookName = ref();
            const value = ref(undefined);
            const borrowers_options = ref();
            const book_name = ref();
            const book_code = ref();
            const book_author = ref();
            const loading = ref(true);
            const hisColumns = [
                {
                    title: '借阅人',
                    dataIndex: 'borrower_name',
                },
                {
                    title: '借书时间',
                    dataIndex: 'borrower_time',
                },
                {
                    title: '还书时间',
                    dataIndex: 'return_time',
                },
                {
                    title: '借阅时长',
                    dataIndex: 'all_time',
                }
            ];
            const columns = [
                {
                    title: 'id',
                    dataIndex: 'id',
                    width: '5%',
                },
                {
                    title: '书名',
                    dataIndex: 'book_name',
                    // width:'20%',
                },
                {
                    title: '书籍编码',
                    dataIndex: 'book_code',
                    width:'10%',
                },
                {
                    title: '作者',
                    dataIndex: 'book_author',
                },
                {
                    title: '借出状态',
                    dataIndex: 'borrow_status',
                    width:'10%',
                    filters:[
                        {text:'空闲',value:'1'},
                        {text:'已借出',value:'0'},
                    ],
                    filterSearch:false,
                    onFilter:(value,record) => record.borrow_status.toString().indexOf(value) === 0 && record.book_valid === 1
                },
                {
                    title: '状态',
                    dataIndex: 'book_valid',
                    width:'10%',
                    filters:[
                        {text:'上架',value:'1'},
                        {text:'下架',value:'0'},
                    ],
                    filterSearch:false,
                    onFilter:(value,record) => record.book_valid.toString().indexOf(value) === 0
                },
                {
                    title: '录入时间',
                    dataIndex: 'creation_ts',
                    width:'10%',
                },
                {
                    title: '操作',
                    dataIndex: 'operation',
                    // width:'15%',
                }
            ];
            const books = ref([]);
            const handAddBook = () => {
                // todo
                if (!book_name.value) {
                    return message.error("请输入新添加书籍名称,不可为空")
                }
                if (!book_code.value) {
                    return message.error("请输入新添加书籍编码,不可为空")
                }
                if (!book_author.value) {
                    return message.error("请输入新添加书籍作者,不可为空")
                }
                loading.value = true;
                axios.post('/re/addBook', { book_name: book_name.value, book_code: book_code.value, book_author: book_author.value })
                    .then(async (response) => {
                        const resp = await axios.post('/re/queryAllBooks')
                        books.value = resp.data.content;
                        bookTotal.value = books.value.length;
                        loading.value = false;
                        book_name.value = null;
                        book_code.value = null;
                        book_author.value = null;
                        return message.success(response.data.content)
                    }
                    )
                modal2Visible.value = false
            }
            const onUpdateBookValid = key => {
                loading.value = true;
                axios.post('/re/updateBookValid', { book_id: key })
                    .then(
                        async (response) => {
                            const resp = await axios.post('/re/queryAllBooks')
                            books.value = resp.data.content;
                            bookTotal.value = books.value.length;
                            loading.value = false;
                            if (response.data.result === 'success') {
                                return message.success(response.data.content)
                            } else if (response.data.result === 'failure') {
                                return message.error(response.data.content)
                            }
                        }
                    )
            }
            const getValidBorrowers = () => {
                const validBorrowers = []
                axios.post('/re/queryAllBorrowers')
                .then((response) => {
                    const allBorrowers = response.data.content
                    for(const borrower of allBorrowers){
                        if (borrower.person_valid == 1){
                            const temp = {}
                            temp['value'] = borrower.id
                            temp['label'] = borrower.person_name
                            validBorrowers.push(temp)
                        }
                    }
                    console.log("getValidBorrowers",validBorrowers)
                    borrowers_options.value = validBorrowers
                    // return validBorrowers
                })
            }
            const filterBorrowOption = (input, option) => {
                console.log("查询借阅人",option.label)
                return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
            };
            const onOpenBorrowModal = (key,b_name) => {
                modal2Borrow.value = true;
                toBeBorrowBookId.value = key;
                toBeBorrowBookName.value = b_name;
                getValidBorrowers()
                console.log("onOpenBorrowModal",borrowers_options.value)

            }
            const handleBorrowFocus = () => {
                console.log("聚焦")
            }
            const handleBorrowBlur = () => {
                console.log("失焦")
            }
            const handleBorrowChange = () => {
                console.log("handlerBorrowerChange")
            }
            const onBorrowBook = () => {
                // todo
                if (! value.value) {
                    return message.error("借阅人不可为空，请选择!")
                }
                loading.value = true;
                console.log("发起借书过程")
                axios.post('/re/borrowBook',{book_id:toBeBorrowBookId.value,borrower_id:value.value})
                .then(async (response) => {
                    const resp = await axios.post('/re/queryAllBooks')
                    books.value = resp.data.content;
                    bookTotal.value = books.value.length;
                    loading.value = false;
                    value.value = undefined
                    if (response.data.result === 'success') {
                        return message.success(response.data.content)
                    } else if (response.data.result === 'failure'){
                        return message.error(response.data.content)
                    }
                })
                modal2Borrow.value = false
            }
            const onReturnBook = key => {
                loading.value = true;
                axios.post('/re/returnBook',{book_id:key})
                .then(
                    async (response) => {
                        const resp = await axios.post('/re/queryAllBooks')
                        books.value = resp.data.content;
                        bookTotal.value = books.value.length;
                        loading.value = false;
                        if (response.data.result === 'success'){
                            return message.success(response.data.content)
                        } else if (response.data.result === 'failure') {
                            return message.error(response.data.content)
                        }
                    }
                )
            }
            const getBookBorrowedHis = id => {
                loading.value = true;
                const his = []
                axios.post('/re/queryBookHis',{book_id:id})
                .then(response => {
                    const resp = response.data.content
                    for(const e of resp){
                        const temp = {}
                        temp['borrower_name'] = e.borrower_name;
                        temp['borrower_time'] = e.borrower_time;
                        temp['return_time'] = e.return_time
                        // 如果有归还时间，还书时间 - 借书时间；如果没有归还时间，当前时间 - 借书时间
                        if (e.return_time){
                            const r_t = e.return_time
                            const b_t = e.borrower_time

                            const retTime = r_t.substr(0,4) + "-" + r_t.substr(4,2) + "-" + r_t.substr(6,2) + " " + r_t.substr(8,2) + ":" + r_t.substr(10,2) + ":" + r_t.substr(12)
                            console.log("retTime:",retTime)

                            const borrTime = b_t.substr(0,4) + "-" + b_t.substr(4,2) + "-" + b_t.substr(6,2) + " " + b_t.substr(8,2) + ":" + b_t.substr(10,2) + ":" + b_t.substr(12)
                            console.log("borrTime:",borrTime)
                            temp['all_time'] = Math.ceil((new Date(retTime) - new Date(borrTime))/1000/3600/24)
                            // console.log(temp['all_time'])
                        } else {
                            const b_t = e.borrower_time
                            const borrTime = b_t.substr(0,4) + "-" + b_t.substr(4,2) + "-" + b_t.substr(6,2) + " " + b_t.substr(8,2) + ":" + b_t.substr(10,2) + ":" + b_t.substr(12)
                            temp['all_time'] = Math.ceil((new Date() - new Date(borrTime))/1000/3600/24)
                            // console.log(temp['all_time'])
                        }
                        his.push(temp)
                    }
                    bookBorrowedHis.value = his;
                    bookHisTotal.value = bookBorrowedHis.value.length;
                    loading.value = false;
                })
            }
            const onOpenBookBorrowedHisModal = (id,name) => {

                modal2BorrowedHis.value = true;
                hisBookName.value = name;
                getBookBorrowedHis(id)


            }
            onMounted(async () => {
                const resp = await axios.post('/re/queryAllBooks')
                books.value = resp.data.content;
                bookTotal.value = books.value.length;
                loading.value = false;
            })
            return {
                zhCN,
                bookTotal,
                bookHisTotal,
                columns,
                hisColumns,
                loading,
                books,
                modal2Visible,
                modal2Borrow,
                modal2BorrowedHis,
                book_name,
                book_code,
                book_author,
                toBeBorrowBookId,
                toBeBorrowBookName,
                value,
                borrowers_options,
                filterBorrowOption,
                bookBorrowedHis,
                hisBookName,
                handAddBook,
                onUpdateBookValid,
                onReturnBook,
                onOpenBorrowModal,
                onBorrowBook,
                handleBorrowFocus,
                handleBorrowBlur,
                handleBorrowChange,
                onOpenBookBorrowedHisModal,
            }
        }
    }
)
</script>

<style scoped>
.editable-add-btn {
    margin-bottom: 8px;
    float: right;
    margin-right:15px;
}
.ant-table-striped :deep(.table-striped) td {
  background-color: #fafafa;
}
.ant-table-striped {
    margin:15px;
}
</style>